package cs.java.json;

import static cs.java.lang.Lang.exception;
import static cs.java.lang.Lang.is;
import static cs.java.lang.Lang.json;

public abstract class JsonObjectImplBase extends JSONTypeImpl implements JSONObject {
	public JsonObjectImplBase(Object value) {
		super(value);
	}

	protected abstract JSONType getImpl(String key);

	@Override public boolean contains(String key) {
		return is(get(key));
	}

	public JSONType get(String key) {
		return getImpl(key);
	}

	@Override public JSONArray getArray(String key) {
		JSONType value = get(key);
		if (is(value)) {
			JSONArray typevalue = value.asArray();
			if (is(typevalue)) return typevalue;
			throw exception("Expected JSONObject, found ", value.getValue());
		}
		return null;
	}

	@Override public Boolean getBoolean(String key) {
		JSONType value = get(key);
		if (is(value)) {
			JSONBoolean typevalue = value.asJSONBoolean();
			if (is(typevalue)) return typevalue.get();
			throw exception("Expected Boolean, found ", value.getValue());
		}
		return null;
	}

	@Override public Double getNumber(String key) {
		JSONType value = get(key);
		if (is(value)) {
			JSONNumber typevalue = value.asJSONNumber();
			if (is(typevalue)) return typevalue.get();
			throw exception("Expected Number, found ", value.getValue());
		}
		return null;
	}

	@Override public JSONObject getObject(String key) {
		JSONType value = get(key);
		if (is(value)) {
			JSONObject typevalue = value.asObject();
			if (is(typevalue)) return typevalue;
			throw exception("Expected JSONObject, found ", value.getValue());
		}
		return null;
	}

	@Override public String getString(String key) {
		JSONType value = get(key);
		if (is(value)) {
			JSONString typevalue = value.asJSONString();
			if (is(typevalue)) return typevalue.get();
			throw exception("Expected String, found ", value.getValue());
		}
		return null;
	}

	@Override public void put(String key, boolean value) {
		put(key, json().create(value));
	}

	@Override public void put(String key, double value) {
		put(key, json().create(value));
	}

	@Override public void put(String key, String value) {
		put(key, json().create(value));
	}
}